#include "RingQueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <pthread.h>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

void *ProductorRoutine(void *rq)
{
    // RingQueue<int> *ringqueue = static_cast<RingQueue<int> *>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while(true)
    {
        // version1
        // int data = rand() % 10 + 1;
        // ringqueue->Push(data);
        // std::cout << "生产数据: " << data << std::endl;

        // version2
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand()%oper.size()];
        Task t(x, y, op, mymath);
        // 生产任务
        ringqueue->Push(t);
        std::cout << "生产者派发任务: " << t.toTaskString() << std::endl;
    }
}

void *ConsumerRoutine(void *rq)
{
    // RingQueue<int> *ringqueue = static_cast<RingQueue<int> *>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while(true)
    {
        // version1
        // int data;
        // ringqueue->Pop(&data);
        // std::cout << "消费数据: " << data << std::endl;
        // sleep(1);

        // version2
        Task t;
        ringqueue->Pop(&t);
        std::string data = t();
        std::cout << "消费者消费了一个任务: " << data <<std::endl;
    }
}

int main()
{
    srand((unsigned)time(nullptr) ^ getpid() ^ pthread_self() ^ 0x1256716);
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t p, c;
    pthread_create(&p, nullptr, ProductorRoutine, rq);
    pthread_create(&c, nullptr, ConsumerRoutine, rq);

    pthread_join(p, nullptr);
    pthread_join(c, nullptr);

    return 0;
}